package com.educate.book.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.book.dao.PictureBookDao;
import com.educate.book.model.bo.PictureBookBO;
import com.educate.book.model.po.PictureBook;
import com.educate.book.rpc.api.PictureBookService;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class PictureBookServiceImpl implements PictureBookService {

    @Resource PictureBookDao pictureBookDao;

    @Override
    public void create(PictureBookBO bo) {
        pictureBookDao.insert(bo);
    }

    @Override
    public void delete(PictureBookBO bo) {
        pictureBookDao.delete(bo);
    }

    @Override
    public void delete(String pictureBookId) {
        pictureBookDao.deleteById(pictureBookId);
    }

    @Override
    public PictureBookBO detail(String pictureBookId) {
        Optional<PictureBook> optional = pictureBookDao.findById(pictureBookId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new PictureBookBO(optional.get());
    }

    @Override
    public PictureBookBO detail(PictureBookBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(PictureBookBO bo) {
        Optional<PictureBook> optional = pictureBookDao.findById(bo.getPictureBookId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        pictureBookDao.save(optional.get());
    }

    @Override
    public Page<PictureBookBO> query(PictureBookBO bo, PageRequest pageRequest) {
        return pictureBookDao.query(bo, pageRequest).map(PictureBookBO::new);
    }

    @Override
    public List<PictureBookBO> list(PictureBookBO bo) {
        List<PictureBook> result = pictureBookDao.findAll();
        return ListUtils.map(result, PictureBookBO::new);
    }
}
